package com.yuanfeng.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.yuanfeng.business.dto.FxGoodsInfoDTO;
import com.yuanfeng.business.dto.OperateFxGoodsDTO;
import com.yuanfeng.business.entity.ShopFxGoodsInfoEntity;
import com.yuanfeng.business.feign.ActivityServiceClient;
import com.yuanfeng.business.mapper.ShopFxGoodsInfoMapper;
import com.yuanfeng.business.service.ShopFxGoodsInfoService;
import com.yuanfeng.business.vo.GoodsListVO;
import com.yuanfeng.commoms.dto.goods.AppSeckillGoodsVO;
import com.yuanfeng.commoms.dto.goods.FxGoodsListDTO;
import com.yuanfeng.commoms.util.Constant;
import com.yuanfeng.commoms.util.Json.JsonUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.vo.activity.AppDiscountGoodsQueryResultVO;
import com.yuanfeng.commoms.vo.activity.AppPintuanGoodsQueryResultVO;
import com.yuanfeng.commoms.vo.fx.ShareGoodsVO;
import com.yuanfeng.commoms.vo.goods.FXGoodsListVO;
import com.yuanfeng.commoms.vo.goodscat.GoodsCatSearchChildVO;
import com.yuanfeng.commoms.vo.goodscat.WebCatMenuVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName ShopFxGoodsInfoServiceImpl
 * @Description
 * @Author cyp
 * @Date 2023-06-05 11:43:19
 * @Version 1.0
 **/
@Service
public class ShopFxGoodsInfoServiceImpl extends ServiceImpl<ShopFxGoodsInfoMapper, ShopFxGoodsInfoEntity>
        implements ShopFxGoodsInfoService {

    @Autowired
    private ActivityServiceClient activityServiceClient;

    @Override
    public ResponseResult updateFxGoodsSaleNum(String data) {
        List<ShareGoodsVO> shareGoodsList = JSON.parseArray(data, ShareGoodsVO.class);
        int result = this.baseMapper.updateGoodsSaleNum(shareGoodsList);
        if (result > 0) {
            return ResponseResult.success("操作成功");
        }
        return ResponseResult.fail(2,"操作失败");
    }

    @Override
    public ResponseResult getFxGoodsInfo(FxGoodsInfoDTO param) {
        Page<FxGoodsInfoDTO> page = new Page<>(param.getPage(), param.getLimit());
        IPage<FxGoodsInfoDTO> list = this.baseMapper.queryFxGoodsList(page,param);
        return ResponseResult.success(PageUtils.getPage(list));
    }

    @Override
    public ResponseResult queryShopGoodsList(FxGoodsInfoDTO param) {
        Page<GoodsListVO> page = new Page<>(param.getPage(), param.getLimit());
        IPage<GoodsListVO> goodsList = this.baseMapper.queryFxGoods(page,param);
        return ResponseResult.success(PageUtils.getPage(goodsList));
    }

    @Override
    public ResponseResult addRemoveFxGoods(OperateFxGoodsDTO param) {
        // 查询分销商品是否存在
        FxGoodsInfoDTO queryFxGoodsInfo = new FxGoodsInfoDTO(null, param.getShopId(), param.getGoodsId());
        List<FxGoodsInfoDTO> fxGoodsInfoList = this.baseMapper.queryFxGoodsListNoLimit(queryFxGoodsInfo);
        if (param.getOperaType() == 1 || param.getOperaType() == 3) {
            // 添加分销商品
            List<GoodsListVO> goodsList = this.baseMapper.queryFxGoodsNoLimit(queryFxGoodsInfo);
            System.out.println(goodsList);
            if (null != goodsList && goodsList.size() == 1) {
                FxGoodsInfoDTO fxGoodsInfo = new FxGoodsInfoDTO(goodsList.get(0), param);
                if (param.getOperaType() == 1 || CollectionUtils.isEmpty(fxGoodsInfoList)) {
                    this.baseMapper.insertSelective(fxGoodsInfo);
                } else {
                    fxGoodsInfo.setId(fxGoodsInfoList.get(0).getId());
                    this.baseMapper.updateByPrimaryKeySelective(fxGoodsInfo);
                }
            }
        } else if (param.getOperaType() == 2) {
            // 商品下架移除
            if (CollectionUtils.isEmpty(fxGoodsInfoList)) {
                return ResponseResult.fail(2,"商品不存在");
            } else {
                FxGoodsInfoDTO updateFxGoods = new FxGoodsInfoDTO(fxGoodsInfoList.get(0).getId(), 2);
                this.baseMapper.updateByPrimaryKeySelective(updateFxGoods);
            }
        } else {
            this.baseMapper.deleteById(param.getFxId());
        }
        return ResponseResult.success(1,"操作成功");
    }

    @Override
    public ResponseResult addRemoveFxGoodsBatch(OperateFxGoodsDTO param) {
        if (CollectionUtils.isEmpty(param.getGoodsIdList())) {
            return ResponseResult.fail(2,"数据错误");
        }

        //查询待操作商品信息
        List<GoodsListVO> goodsList = this.baseMapper.queryFxGoodsBatch(param.getShopId(), param.getGoodsIdList());

        List<Integer> goodsIdList = goodsList.stream().map(GoodsListVO::getGoodsId).collect(Collectors.toList());

        List<FxGoodsInfoDTO> addFxGoods = new ArrayList<>();
        if (param.getOperaType() == 1) {
            // 查询已存在的分销商品
            List<FxGoodsInfoDTO> fxGoodsInfoList = this.baseMapper.queryFxGoodsListBatch(goodsIdList,null);
            List<Integer> updateGoodsIdList = fxGoodsInfoList.stream().map(FxGoodsInfoDTO::getGoodsId).collect(Collectors.toList());

            for (GoodsListVO goods : goodsList) {
                if(!updateGoodsIdList.contains(goods.getGoodsId())){
                    // 添加分销商品
                    FxGoodsInfoDTO fxGoodsInfo = new FxGoodsInfoDTO(goods, param);
                    addFxGoods.add(fxGoodsInfo);
                }
            }
            if(!CollectionUtils.isEmpty(addFxGoods)){
                // 批量插入
                this.baseMapper.insertSelectiveBatch(addFxGoods);
            }

            if(!CollectionUtils.isEmpty(updateGoodsIdList)){
                // 批量更新
                param.setGoodsIdList(updateGoodsIdList);
                this.baseMapper.fxGoodsPutawayBatch(param);
            }
        } else if(param.getOperaType().intValue() == 2){
            this.baseMapper.soldOutBatch(param.getGoodsIdList());
        }else{
            this.baseMapper.deleteBatch(param.getGoodsIdList());
        }
        return ResponseResult.success(1,"操作成功");
    }

    @Override
    public ResponseResult fxGoodsList(FxGoodsListDTO goodsListRequest) {
        if(null != goodsListRequest.getCatId()) {
            List<Integer> catIds = this.queryCatList(goodsListRequest.getCatId());
            if (!CollectionUtils.isEmpty(catIds)) {
                goodsListRequest.setCatIds(catIds);
                goodsListRequest.setCatId(0);
            }
        }
        Page<FXGoodsListVO> page = new Page<>(goodsListRequest.getPage(), goodsListRequest.getLimit());
        IPage<FXGoodsListVO> fxGoodsList = this.baseMapper.findFxGoodsList(page,goodsListRequest);
        for (FXGoodsListVO goodsList : fxGoodsList.getRecords()) {
            //秒杀
            if( null != goodsList.getCommonIsXian() &&  goodsList.getCommonIsXian().equals(2)){
                Map<String, Object> map = new HashMap<>();
                map.put("goodsId",goodsList.getGoodsId());
                AppSeckillGoodsVO seckillGoods = activityServiceClient.selectByGoodsId(map);
                if(null != seckillGoods && null != seckillGoods.getSeckillPrice()){
                    goodsList.setGoodsPrice(seckillGoods.getSeckillPrice());
                }
            }
            //限时折扣
            if( null != goodsList.getCommonIsXian() && goodsList.getCommonIsXian().equals(3)){
                AppDiscountGoodsQueryResultVO discountGoods = this.baseMapper.selectByGoodsId2(goodsList.getGoodsId());
                if(null != discountGoods && null != discountGoods.getDiscountPrice()){
                    goodsList.setGoodsPrice(discountGoods.getDiscountPrice());
                }
            }
            //拼团
            if( null != goodsList.getCommonIsXian() && goodsList.getCommonIsXian().equals(4)){
                AppPintuanGoodsQueryResultVO pintuanGoods = this.baseMapper.selectPintuanGoodsDetail(goodsList.getCommonId(), goodsList.getGoodsId());
                if(null != pintuanGoods && null != pintuanGoods.getPrice()){
                    goodsList.setGoodsPrice(pintuanGoods.getPrice());
                }
            }
        }
        return ResponseResult.success(PageUtils.getPage(fxGoodsList));
    }

    public List<Integer> queryCatList(Integer catId){
        List<Integer> catIds;
        List<WebCatMenuVO> allMenu;
        GoodsCatSearchChildVO goodsCatSearchChild;
        // 从缓存中获取
        String cacheCatIds = RedisUtil.get(Constant.CACHE_GOODS_WEB_GOODS_LIST_HEADER_PREFIX + "_" + catId);
        if (null != cacheCatIds && !cacheCatIds.equals("")) {
            goodsCatSearchChild = JsonUtils.string2Obj(cacheCatIds, GoodsCatSearchChildVO.class);
            catIds = goodsCatSearchChild.getCatIds();
        } else {
            allMenu = this.baseMapper.selectAllCat2();
            catIds = this.getMenuList(allMenu, catId);
            goodsCatSearchChild = new GoodsCatSearchChildVO();
            goodsCatSearchChild.setAllMenu(allMenu);
            goodsCatSearchChild.setCatIds(catIds);
            RedisUtil.set(Constant.CACHE_GOODS_WEB_GOODS_LIST_HEADER_PREFIX + "_" + catId, JsonUtils.toString(goodsCatSearchChild), RedisUtil.EXRP_MONTH);
        }
        if (!CollectionUtils.isEmpty(catIds)) {
            catIds.add(catId);
        }
        return catIds;
    }

    /**
     * 获取商品分类所有的子分类
     *
     * @param allMenu
     * @param catId
     * @return
     */
    public List<Integer> getMenuList(List<WebCatMenuVO> allMenu, Integer catId) {
        List<Integer> allChildCatIds = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(allMenu)) {
            for (WebCatMenuVO catMenu : allMenu) {
                if (catMenu.getCatId().equals(catId)) {
                    allChildCatIds.add(catId);
                    getChild(allMenu, catMenu.getCatId(), allChildCatIds);
                }
            }
        }
        return allChildCatIds;

    }

    /**
     * 找出子菜单
     * @param allMenu
     * @param parentId
     * @param allChildCatIds
     * @return
     */
    private List<Integer> getChild(List<WebCatMenuVO> allMenu, Integer parentId, List<Integer> allChildCatIds) {
        List<Integer> childList = Lists.newArrayList();
        for (WebCatMenuVO catMenu : allMenu) {
            if (catMenu.getCatParentId().equals(parentId)) {
                allChildCatIds.add(catMenu.getCatId());
                childList.add(catMenu.getCatId());
                getChild(allMenu, catMenu.getCatId(), allChildCatIds);
            }
        }
        if (CollectionUtils.isEmpty(childList)) {
            return null;
        }
        return allChildCatIds;
    }
}
